<?php

namespace app\admin\controller\medicine;

use app\common\controller\Backend;
use think\Db;

/**
 * 库存查询
 *
 * @icon fa fa-circle-o
 */
class Storage extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Storage;
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $a = json_decode(request()->param()['filter'],true);
            $b = json_decode(request()->param()['op'],true);
            $filter = '';
            $op = '';

            if (isset($a['medicine.count'])){
                if ($a['medicine.count'] == 1){
                    $orders['medicine.count'] = 'desc';
                }else{
                    $orders['medicine.count'] = 'asc';
                }
                unset($a['medicine.count']);
                unset($b['medicine.count']);


               $filter = json_encode($a);
               $op = json_encode($b);

            }else{
                $orders['id'] = 'desc';
            }

            if (isset(request()->param()['date'])){
                $wheres['end_time'] = ['<=',request()->param()['date']];
            }else{
                $wheres = [];
            }

            if (isset(request()->param()['status'])){
                $wheress['quantity'] = ['<=',10];
            }else{
                $wheress = [];
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams($filter,$op);
            //list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                //->with(["medicine"=>['id','code','medicine_name','specification','supplier_name','model_number','type','count']])
                ->with([
                    'medicine' => function ($query) {
                        $query->withField('id,code,medicine_name,specification,supplier_name,model_number,type,count');
                    }
                ])
                ->where($where)
                ->where($wheres)
                ->where($wheress)
                ->where('medicine.is_del',0)
                //->order(['storage.id'=>'desc','medicine.count'=>'desc'])
                ->order($orders)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $type = $params['type'];
                $count = $params['count'];
                unset($params['type']);
                unset($params['count']);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    if ($type == 2){
                        if (($row->quantity-$count) < 0){
                            Db::rollback();
                            $this->error(__('库存数量不足'));
                        }

                        Db::table('fa_medicine')
                            ->where('id',$row->medicine_id)
                            ->setDec('count',$count);

                        Db::table('fa_storage')
                            ->where('id',$row->id)
                            ->setDec('quantity',$count);

                        Db::table('fa_storage')
                            ->where('id',$row->id)
                            ->setDec('counts',$count);
                    }else{
                        Db::table('fa_medicine')
                            ->where('id',$row->medicine_id)
                            ->setInc('count',$count);

                        Db::table('fa_storage')
                            ->where('id',$row->id)
                            ->setInc('quantity',$count);

                        Db::table('fa_storage')
                            ->where('id',$row->id)
                            ->setInc('counts',$count);
                    }

                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
